package com.lw.leetcode.tree.b;


import com.lw.leetcode.tree.Node;

/**
 * 剑指 Offer 35. 复杂链表的复制
 * 138. 复制带随机指针的链表
 *
 * @Author liw
 * @Date 2021/4/29 14:44
 * @Version 1.0
 */
public class CopyRandomList {

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
      Node node = head;
        while (node != null) {
            int val = node.val;
          Node item = new Node(val);
            item.next = node.next;
            item.random = node.random;
            node.next = item;
            node = item.next;
        }
        node = head.next;
        while (node != null && node.next != null) {
            Node random = node.random;
            if (random != null) {
                node.random = random.next;
            }
            node = node.next.next;
        }
        if (node != null) {
            Node random = node.random;
            if (random != null) {
                node.random = random.next;
            }
        }
        node = head.next;
        Node a = head;
        Node b = head.next;
        while (b != null && b.next != null) {
            a.next = a.next.next;
            b.next = b.next.next;
            a = a.next;
            b = b.next;
        }
        a.next = null;
        return node;
    }

}
